package antoine.ear.exo.recoaccords;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.Sequence;
import javax.sound.midi.Track;

import antoine.ear.GUI;
import antoine.ear.Main;
import antoine.ear.exo.Exo;
import antoine.ear.generator.ChordGenerator;
import antoine.ear.generator.NoteGenerator;
import antoine.ear.generator.SequenceGenerator;
import antoine.ear.generator.chords.Dom7Generator;
import antoine.ear.generator.chords.Maj7Generator;
import antoine.ear.generator.chords.Min7Generator;
import antoine.ear.generator.sequences.MixolydianSequenceGenerator;

public class RecoChordsMelo extends Exo{
	
	public int nbChords = 2;
	
	public RecoChordsMelo(int tempo, int octave, int aNbChords) {
		this.nbChords = aNbChords;
		this.tempo = tempo;
		this.octave = octave;
		try {
			this.generate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getPrintableResult() {
		return soluce;
	}

	public void generate() throws Exception {
		try {
			GUI gui = GUI.getInstance();
			Sequence seq = new Sequence(Sequence.PPQ, 1);
			Track track = seq.createTrack();
				
			Random random = new Random();

			int note = 36+random.nextInt(12);
			indication = NoteGenerator.getNoteName(note);

			for (int i=0;i<nbChords;i++){
				
				track.add(createNoteOnEvent(note, 0+i*3));
				track.add(createNoteOffEvent(note, 3+i*3));
				track.add(createMetaMessOnEvent(note, 0+i*3, ACTIVATENOTE));
	            track.add(createMetaMessOnEvent(note, 3+i*3, DESACTIVATENOTE));
	            
				int ind = random.nextInt(gui.selectedChords.size());
				ChordGenerator gene = (ChordGenerator)gui.selectedChords.toArray()[ind];
				gene.reinit();
				
				Iterator ite = gene.generate(note%12, 0+i*3, 3).iterator();
				while (ite.hasNext()){
					track.add((MidiEvent) ite.next());
				}
				
				SequenceGenerator seqgene = gene.sequenceGenerator;
				Iterator ite2 = GUI.unselectedIntervals.iterator();
				while (ite2.hasNext()){
					Integer inte = (Integer) ite2.next();
					seqgene.removeNoteInMode(inte.intValue());
				}
				if (seqgene!=null){
					seqgene.tickOffset = i*3;
					ite = seqgene.generate(Integer.parseInt((String)GUI.nbNotes.getSelectedItem()), note%12, 5).iterator();
					while (ite.hasNext()){
						track.add((MidiEvent) ite.next());
					}
					this.soluce += gene.chordName()+"_"+seqgene.seqName()+" | ";
				}

				note = 36+random.nextInt(12);
			}
		
			this.setSequence(seq);
			setTempo(tempo);
		} catch (InvalidMidiDataException e) {
			throw new Exception(e); 
		}
	}

	public String getIndication() {
		return "La basse est " + indication;
	}
}
